<?php

namespace App\Http\Model;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class WishWheel extends Base
{
    protected $table = 'wish_wheel_config';
    protected $wPoolTable = 'wish_wheel_pool';
    protected $wPoolConfigTable = 'wish_wheel_pool_config';
    protected $wOrderTable = 'wish_wheel_order';
    protected $wDrawTable = 'wish_wheel_draw';
    protected $wWhiteTable = 'wish_wheel_white';
    protected $wStatisticsTable = 'wish_wheel_statistics';
    protected $giftTable = 'gift_library';
    protected $wGiftTable = 'wish_wheel_gift';//展示礼物表
    protected $wPoolUserTable = 'wish_wheel_pool_user';//个人池用户
    protected $wPoolWhiteTable = 'wish_wheel_pool_white';//波波球奖池白名单
    protected $wPoolExtractTable = 'wish_wheel_extract_pool';//波波球抽取奖池
    protected $wPoolExtractLogTable = 'wish_wheel_extract_pool_log';//波波球抽取奖池记录
    protected $wPoolExtractUserTable = 'wish_wheel_extract_pool_user';//波波球抽取奖池用户

    //波波球配置缓存
    protected $wishWheelConfigKey = 'WISHWHEEL:CONFIG';//string WISHWHEEL:CONFIG => {string}
    //波波球奖池缓存
    protected $wishWheelPoolKey = 'WISHWHEEL:POOL';//string WISHWHEEL:POOL => {string}
    //波波球奖池配置缓存
    protected $wishWheelPoolConfigKey = 'WISHWHEEL:POOLCONFIG:';//string WISHWHEEL:POOLCONFIG:{poolId} => {string}
    //波波球奖池配置数据缓存
    public $wishWheelPoolDataKey = '{WISHWHEEL:POOLDATA:%s}'; //奖池 {WISHWHEEL:POOLDATA:{poolId}}
    //波波球个人奖池
    public $wishWheelSelfPoolDataKey = '{WISHWHEEL:USERPOOLDATA:%s:%s}';//奖池 {WISHWHEEL:USERPOOLDATA:{userId}:{$poolId}}

    //用户抽奖数
    protected $userDrawNumKey = 'WISHWHEEL:USERDRAW:NUM:';//string WISHWHEEL:USERDRAW:NUM:{userId} => {num}
    //波波球展示礼物缓存
    protected $wishWheelGiftKey = 'WISHWHEEL:GIFTCONFIG';//string WISHWHEEL:GIFTCONFIG => {string}
    //波波球用户每周抽奖次数缓存
    protected $userDrawNumWeekKey = 'WISHWHEEL:USERDRAW:WEEKNUM:';//string WISHWHEEL:USERDRAW:WEEKNUM:{ymd}:{userid} => {num}
    //波波球用户每日抽奖数据统计缓存
    protected $userDrawNumDayKey = 'WISHWHEEL:USERDRAW:DAYNUM:';//hash WISHWHEEL:USERDRAW:DAYNUM:{ymd}:{userid} => {draw_no/prop_diamond_num/reward_diamond_num}
    //波波球抽取奖池奖品池缓存
    protected $wishWheelExtractPoolDataKey = 'WISHWHEEL:EXTRACTPOOLDATA:';//set WISHWHEEL:EXTRACTPOOLDATA:{extractPoolId} => {num}

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    //编辑波波球配置
    public function editWishWheelConfig($params)
    {
        $upData = [];
        if(!empty($params['need_num'])) {
            $upData['need_num'] = $params['need_num'];
        }
        if(isset($params['new_num'])) {
            $upData['new_num'] = $params['new_num'];
        }
        // if(intval($params['draw_num_1'])) {
            $upData['draw_num_1'] = $params['draw_num_1'];
        // }
        // if(intval($params['draw_num_2'])>0) {
            $upData['draw_num_2'] = $params['draw_num_2'];
        // }
        // if(intval($params['draw_num_3'])>0) {
            $upData['draw_num_3'] = $params['draw_num_3'];
        // }
        if(!empty($params['draw_img_1a'])) {
            $upData['draw_img_1a'] = $params['draw_img_1a'];
        }
        if(!empty($params['draw_img_1b'])) {
            $upData['draw_img_1b'] = $params['draw_img_1b'];
        }
        if(!empty($params['draw_img_2a'])) {
            $upData['draw_img_2a'] = $params['draw_img_2a'];
        }
        if(!empty($params['draw_img_2b'])) {
            $upData['draw_img_2b'] = $params['draw_img_2b'];
        }
        if(!empty($params['draw_img_3a'])) {
            $upData['draw_img_3a'] = $params['draw_img_3a'];
        }
        if(!empty($params['draw_img_3b'])) {
            $upData['draw_img_3b'] = $params['draw_img_3b'];
        }
        if(isset($params['full_rate'])) {
            $upData['full_rate'] = $params['full_rate'];
        }
        if(isset($params['in_profit_loss'])) {
            $upData['in_profit_loss'] = $params['in_profit_loss'];
        }
        if(isset($params['in_profit_rate'])) {
            $upData['in_profit_rate'] = $params['in_profit_rate'];
        }
        if(isset($params['out_profit_loss'])) {
            $upData['out_profit_loss'] = $params['out_profit_loss'];
        }
        if(isset($params['out_profit_rate'])) {
            $upData['out_profit_rate'] = $params['out_profit_rate'];
        }

        if(empty($upData)) {
            return 0;
        }

        $res = DB::table($this->table)->update($upData);

        $cacheKey = $this->wishWheelConfigKey;
        Redis::del($cacheKey);

        return $res;
    }

    //新增波波球展示礼物
    public function wishWheelAddGift($giftId, $sort)
    {
        $data = [];
        $data['gift_id'] = $giftId;
        $data['sort'] = $sort;
        $data['is_delete'] = 0;

        $id = DB::table($this->wGiftTable)->insertGetId($data);

        $cacheKey = $this->wishWheelGiftKey;
        Redis::del($cacheKey);

        return $id;
    }

    //波波球删除展示礼物
    public function wishWheelDelGift($id)
    {
        $id = DB::table($this->wGiftTable)->where('id', $id)->update(['is_delete'=>1]);

        $cacheKey = $this->wishWheelGiftKey;
        Redis::del($cacheKey);

        return $id;
    }

    /**
     * 获取波波球展示礼物
     */
    public function getWishWheelGift(){
        $key = $this->wishWheelGiftKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->wGiftTable.' as a')
            ->leftJoin($this->giftTable.' as b','a.gift_id','=','b.gift_id')
            ->where('a.is_delete', 0)
            ->orderBy('b.price', 'desc')->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
               Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        return $list;
    }

    //新增波波球奖池
    public function addWishWheelPool($poolName, $minNum, $maxNum, $poolType, $ifDefault)
    {
        $data = [];
        $data['pool_name'] = $poolName;
        $data['min_num'] = $minNum;
        $data['max_num'] = $maxNum;
        $data['pool_type'] = $poolType;
        $data['if_default'] = $ifDefault;
        $data['status'] = 2;

        $id = DB::table($this->wPoolTable)->insertGetId($data);

        $cacheKey = $this->wishWheelPoolKey;
        Redis::del($cacheKey);

        return $id;
    }

    //编辑波波球奖池
    public function editWishWheelPool($id, $params)
    {
        $upData = [];
        if(!empty($params['status'])) {
            $upData['status'] = $params['status'];
        }
        if(!empty($params['pool_name'])) {
            $upData['pool_name'] = $params['pool_name'];
        }
        if(!empty($params['min_num'])) {
            $upData['min_num'] = $params['min_num'];
        }
        if(!empty($params['max_num'])) {
            $upData['max_num'] = $params['max_num'];
        }
        if(!empty($params['if_default'])) {
            $upData['if_default'] = $params['if_default'];
        }
        if(isset($params['in_profit_loss'])) {
            $upData['in_profit_loss'] = $params['in_profit_loss'];
        }
        if(isset($params['in_profit_rate'])) {
            $upData['in_profit_rate'] = $params['in_profit_rate'];
        }
        if(isset($params['out_profit_rate'])) {
            $upData['out_profit_rate'] = $params['out_profit_rate'];
        }

        if(empty($upData)) {
            return 0;
        }

        $res = DB::table($this->wPoolTable)->where('id', $id)->update($upData);

        $cacheKey = $this->wishWheelPoolKey;
        Redis::del($cacheKey);

        return $res;
    }

    //新增波波球奖池配置
    public function addWishWheelPoolConfig($poolId, $itemNo)
    {
        $data = [];
        $data['pool_id'] = $poolId;
        $data['item_no'] = $itemNo;

        $id = DB::table($this->wPoolConfigTable)->insertGetId($data);

        return $id;
    }

    //编辑波波球奖池配置
    public function editWishWheelPoolConfig($poolId, $id, $giftId, $giftNum)
    {
        $upData = [];
        $upData['gift_id'] = $giftId;
        $upData['gift_num'] = $giftNum;

        $res = DB::table($this->wPoolConfigTable)->where('id', $id)->update($upData);

        $cacheKey = $this->wishWheelPoolConfigKey.$poolId;
        Redis::del($cacheKey);

        return $res;
    }

    /**
     * 获取波波球配置
     */
    public function getWishWheelConfig()
    {
        $key = $this->wishWheelConfigKey;
        $list = Redis::get($key);
        if (empty($list)) {
            $list = DB::table($this->table)->first();
            $list = self::objToArray($list);
            if (!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        } else {
            $list = json_decode($list, true);
        }

        return $list;
    }


    public function updateGameRule($data)
    {
        $gameRule = $data['gameRule'];
        $res = DB::table($this->table)->where("id", "=", '1')->update(['rule' => $gameRule]);
        if ($res) {
            $key = $this->wishWheelConfigKey;
            $list = DB::table($this->table)->first();
            $list = self::objToArray($list);
            if (!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }
    }

    public function getGameRule()
    {
        $key = $this->wishWheelConfigKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->table)->first();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key,86400, json_encode($list));
            }
        }

        return $list;
    }



    /**
     * 获取波波球奖池
     */
    public function getWishWheelPool(){
        $key = $this->wishWheelPoolKey;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->wPoolTable)->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        $list = array_column($list, null, 'id');

        return $list;
    }

    /**
     * 获取波波球奖池配置
     */
    public function getWishWheelPoolConfig($poolId){
        $key = $this->wishWheelPoolConfigKey.$poolId;
        $list = Redis::get($key);
        if(empty($list)){
            $list = DB::table($this->wPoolConfigTable)->where('pool_id', $poolId)->get();
            $list = self::objToArray($list);
            if(!empty($list)) {
                Redis::setex($key, 86400, json_encode($list));
            }
        }else{
            $list = json_decode($list, true);
        }

        return $list;
    }

    /**
     * 初始化波波球奖池配置数据缓存
     */
    public function makeWishWheelPoolData($poolId, $data){
        $key = sprintf($this->wishWheelPoolDataKey, $poolId);
        aliasInit($key, $data);
    }

    /**
     * 波波球奖池配置剩余数量
     */
    public function getWishWheelPoolData($poolId){
        $result = [];
        $key = sprintf($this->wishWheelPoolDataKey, $poolId);
        $nameKey = $key . ':ALIAS:' . 'KEYNAME';
        $valKey = Redis::GET($nameKey);
        if(!empty($valKey)) {
            if(Redis::EXISTS($valKey)) {
                $list = Redis::LRANGE($valKey, 0, -1);
                if(!empty($list)) {
                    foreach($list as $val) {
                        if(empty($result[$val])) {
                            $result[$val]['id'] = $val;
                            $result[$val]['num'] = 0;
                        }
                        $result[$val]['num'] = $result[$val]['num'] + 1;
                    }
                }
            }
        }
        $result = array_values($result);

        return $result;
    }

    /**
     * 用户总抽奖记录数
     */
    public function getUserWishWheelDrawNum($userId, $cache=0)
    {
        $num = 0;
        $cacheKey = $this->userDrawNumKey.$userId;
        if($cache) {
            $num = Redis::get($cacheKey);
        }
        // if(empty($num)) {
        //     $query = DB::table($this->wOrderTable)
        //         ->where('user_id', $userId);
        //     $num = $query->sum('num');
        // }
        $num = (int) $num;

        //今日剩余时间
        $todDayEnd = Carbon::today()->endOfDay()->toDateTimeString();
        $diffTime = (new Carbon)->diffInSeconds($todDayEnd);
        Redis::set($cacheKey, $num);
        Redis::expire($cacheKey, $diffTime);

        return $num;
    }

    /**
     * 获取波波球用户每周抽奖次数缓存
     */
    public function getUserWishWheelDrawNumByWeek($userId)
    {
        $startWeek = Carbon::today()->startOfWeek()->toDateString();
        $endWeek = Carbon::today()->endOfWeek()->toDateString();
        $cacheKey = $this->userDrawNumWeekKey.$startWeek.'|'.$endWeek.':'.$userId;
        $num = Redis::get($cacheKey);
        if(empty($num)) {
            $query = DB::table($this->wOrderTable)
                ->where('created_at', '>=', $startWeek.' 00:00:00')
                ->where('created_at', '<=',  $endWeek.' 23:59:59')
                ->where('user_id', $userId);
            $num = $query->sum('num');
        }
        $num = (int) $num;

        Redis::set($cacheKey, $num);
        Redis::expire($cacheKey, 14*86400);

        return $num;
    }
    
    //累加波波球用户每周抽奖次数缓存
    public function incrUserDrawWeekNum($userId, $num)
    {
        if($num <= 0) {
            return false;
        }
        $startWeek = Carbon::today()->startOfWeek()->toDateString();
        $endWeek = Carbon::today()->endOfWeek()->toDateString();
        $cacheKey = $this->userDrawNumWeekKey.$startWeek.'|'.$endWeek.':'.$userId;
        $new = Redis::INCRBY($cacheKey, $num);

        return $new;
    }

    //累加用户总抽奖记录数
    public function incrUserDrawNum($userId, $num)
    {
        if($num <= 0) {
            return false;
        }
        $cacheKey = $this->userDrawNumKey.$userId;
        $new = Redis::INCRBY($cacheKey, $num);

        return $new;
    }

    /**
     * 获取用户白名单
     */
    public function getWishWheelWhite($userId){
        $list = DB::table($this->wWhiteTable)
            ->where('user_id', $userId)
            ->where('status', 0)
            ->where('is_delete', 0)
            ->get();
        $list = self::objToArray($list);

        return $list;
    }

    //新增波波球订单记录
    public function addWishWheelOrder($data)
    {
        $id = DB::table($this->wOrderTable)->insertGetId($data);

        return $id;
    }

    //波波球自指定奖池抽取
    public function drawWishWheel($poolId)
    {
        $key = sprintf($this->wishWheelPoolDataKey, $poolId);
        $poolConfigId = aliasIndex($key);

        return $poolConfigId;
    }

    //波波球自指定奖池抽取
    public function drawWishWheelUser($poolId, $userId)
    {
        $key = sprintf($this->wishWheelSelfPoolDataKey, $userId, $poolId);
        $poolConfigId = aliasIndex($key);

        return $poolConfigId;
    }

    //新增波波球抽奖记录
    public function addWishWheelDraw($data)
    {
        $id = DB::table($this->wDrawTable)->insertGetId($data);

        return $id;
    }

    //更新波波球订单记录
    public function updateWishWheelDraw($orderId, $rewardDiamondNum)
    {
        $res = DB::table($this->wOrderTable)->where('id', $orderId)->update(['reward_diamond_num'=>$rewardDiamondNum]);

        return $res;
    }

    //更新波波球白名单
    public function updateWishWheelWhite($id, $orderId)
    {
        $res = DB::table($this->wWhiteTable)->where('id', $id)->update(['status'=>1, 'order_id'=>$orderId]);

        return $res;
    }

    /**
     * 波波球中奖记录列表
     */
    public function awardList($orderId, $limit, $where){
        $query = DB::table($this->wOrderTable);
        if($orderId > 0) {
            $query = $query->where('id', '<', $orderId);
        }
        if(!empty($where['user_id'])) {
            $query = $query->where('user_id', $where['user_id']);
        }
        if(!empty($where['created_at_st'])) {
            $query = $query->where('created_at', '>=', $where['created_at_st']);
        }
        $list = $query->limit($limit)->orderBy('id', 'desc')->get();
        $list = self::objToArray($list);

        $result = [];
        if(!empty($list)) {
            $rankWhere = function($q)use($where) {
                if(!empty($where['created_at_st'])){
                    $q->where('gift_library.price','>=',200);
                }
            };
            $orderIds = array_column($list, 'id');
            $drawList = DB::table($this->wDrawTable)
                ->leftJoin($this->giftTable,$this->wDrawTable . '.gift_id', '=', $this->giftTable . '.gift_id')
                ->whereIn('order_id', $orderIds)
                ->where($rankWhere)
                ->selectRaw('sum(gift_num) as gift_num, order_id, zb_wish_wheel_draw.gift_id, user_id')
                ->groupBy('order_id', 'gift_id')
                ->get();
            $drawList = self::objToArray($drawList);

            $list = array_column($list, null, 'id');

            foreach($drawList as $key=>$val) {
                $val['created_at'] = $list[$val['order_id']]['created_at'];
                $drawList[$key] = $val;
            }

            array_multisort(array_column($drawList, 'order_id'), SORT_DESC, $drawList);

            $result = $drawList;
        }
        return $result;
    }

    //新增波波球白名单
    public function addWishWheelWhite($userId, $giftId, $adminId, $poolId=0)
    {
        $data = [];
        $data['user_id'] = $userId;
        $data['gift_id'] = $giftId;
        $data['admin_id'] = $adminId;
        $data['pool_id'] = $poolId;
        $data['status'] = 0;

        $id = DB::table($this->wWhiteTable)->insertGetId($data);

        return $id;
    }

    //删除波波球白名单
    public function delWishWheelWhite($whiteId)
    {
        $id = DB::table($this->wWhiteTable)->where('id', $whiteId)->where('is_delete', 0)->update(['is_delete'=>1]);

        return $id;
    }

    //取消投放波波球白名单
    public function cancelWishWheelWhite($whiteId)
    {
        $id = DB::table($this->wWhiteTable)->where('id', $whiteId)->where('status', 0)->update(['status'=>1]);

        return $id;
    }

    //统计波波球数据
    public function wishWheelStatistics($dateSt, $dateEt)
    {
        $info = DB::table($this->wOrderTable)
            ->where('created_at', '>=', $dateSt)
            ->where('created_at', '<=', $dateEt)
            ->selectRaw('count(DISTINCT user_id) as user_num, sum(num) as draw_num, sum(prop_num) as prop_num, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num')
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //新增波波球每日统计
    public function addWishWheelStatistics($data)
    {
        $id = DB::table($this->wStatisticsTable)->insertGetId($data);

        return $id;
    }

    /**
     * 波波球中奖记录列表V2
     */
    public function awardListV2($page, $limit, $where){
        $query = DB::table($this->wDrawTable);
        $query = $query->where('reward_diamond_num', '>=', 5200);
        if(!empty($where['user_id'])) {
            $query = $query->where('user_id', $where['user_id']);
        }
        if(!empty($where['created_at_st'])) {
            $query = $query->where('created_at', '>=', $where['created_at_st']);
        }
        $query = $query->selectRaw('sum(gift_num) as gift_num, order_id, gift_id, user_id, created_at')
            ->groupBy('order_id', 'gift_id')
            ->orderBy('order_id', 'desc')
            ->offset($page * $limit)->limit($limit);
        $drawList = $query->get();
        $result = self::objToArray($drawList);

        return $result;
    }

    /**
     * 波波球订单中奖记录列表
     */
    public function orderAwardList($orderId){
        $info = DB::table($this->wOrderTable)->where('id', $orderId)->first();
        $info = self::objToArray($info);
        if(empty($info)) {
            return [];
        }

        $drawList = DB::table($this->wDrawTable)
            ->where('order_id', $orderId)
            ->selectRaw('sum(gift_num) as gift_num, sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num, gift_id')
            ->groupBy('gift_id')
            ->get();
        $drawList = self::objToArray($drawList);
        if(empty($drawList)) {
            return [];
        }
        $info['drawList'] = $drawList;

        return $info;
    }

    //获取波波球个人池用户
    public function getWishWheelPoolUser($userId)
    {
        $info = DB::table($this->wPoolUserTable)
            ->where('user_id', $userId)
            ->where('is_delete', 0)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //新增波波球个人池用户
    public function addWishWheelPoolUser($userId, $adminId, $poolId, $outDiamondNum)
    {
        $data = [];
        $data['user_id'] = $userId;
        $data['add_time'] = date('Y-m-d H:i:s', time());
        $data['admin_id'] = $adminId;
        $data['pool_id'] = (int) $poolId;
        $data['out_diamond_num'] = (int) $outDiamondNum;

        $id = DB::table($this->wPoolUserTable)->insertGetId($data);

        return $id;
    }

    //波波球删除个人池用户
    public function wishWheelDelPoolUser($id, $userId, $adminId)
    {
        $update = [];
        $update['deladmin_id'] = $adminId;
        $update['del_time'] = date('Y-m-d H:i:s', time());
        $update['is_delete'] = 1;

        $res = DB::table($this->wPoolUserTable)->where('id', $id)->update($update);
        if($res) {
            $keys = Redis::Keys('{WISHWHEEL:USERPOOLDATA:'.$userId.':*');
            foreach ($keys as $key) {
                Redis::expire($key, 86400*60);
            }
        }

        return $res;
    }

    /**
     * 初始化波波球个人奖池配置数据缓存
     */
    public function makeWishWheelSelfPoolData($poolId, $data){
        //查询个人池用户列表
        $list = DB::table($this->wPoolUserTable)->where('is_delete',0)->where('pool_id', $poolId)->get();
        $list = self::objToArray($list);
        if(empty($list)){
            return false;
        }
        foreach($list as $v){
            $key = sprintf($this->wishWheelSelfPoolDataKey, $v['user_id'], $poolId);
            aliasInit($key, $data);
        } 
        return true;
    }

    /**
     * 初始化波波球个人奖池配置数据缓存指定用户
     */
    public function makeWishWheelSelfPoolDataByPoolIdUserId($poolId, $userId, $data){
        $key = sprintf($this->wishWheelSelfPoolDataKey, $userId, $poolId);
        aliasInit($key, $data);
        return true;
    }

    //查看个人奖池剩余数量
    public function getWishWheelSelfPoolData($poolId, $userId){
        $result = [];
        $key = sprintf($this->wishWheelSelfPoolDataKey, $userId, $poolId);
        $nameKey = $key . ':ALIAS:' . 'KEYNAME';
        $valKey = Redis::GET($nameKey);
        if(!empty($valKey)) {
            if(Redis::EXISTS($valKey)) {
                $list = Redis::LRANGE($valKey, 0, -1);
                if(!empty($list)) {
                    foreach($list as $val) {
                        if(empty($result[$val])) {
                            $result[$val]['id'] = $val;
                            $result[$val]['num'] = 0;
                        }
                        $result[$val]['num'] = $result[$val]['num'] + 1;
                    }
                }
            }
        }
        $result = array_values($result);

        return $result;
    }

    //获取波波球用户的个人池ID
    public function getWishWheelPoolUserId($userId)
    {
        $info = DB::table($this->wPoolUserTable)
            ->where('user_id', $userId)
            ->where('is_delete', 0)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //波波球自指定奖池中抽取指定的余量
    public function drawWishWheelAppoint($poolId, $poolConfigId, $userId=0)
    {
        if(empty($userId)) {
            $key = sprintf($this->wishWheelPoolDataKey, $poolId);
        }else{
            $key = sprintf($this->wishWheelSelfPoolDataKey, $userId, $poolId);
        }
        $nameKey = $key . ':ALIAS:' . 'KEYNAME';
        $valKey = Redis::GET($nameKey);
        //移除指定参数
        $res = Redis::LREM($valKey, 1, $poolConfigId);
        if($res) {
            //加入另一个池子
            $key_0 = $key.':ALIAS:0';
            $key_1 = $key.':ALIAS:1';
            if($valKey === $key_0) {
                Redis::lpush($key_1, $poolConfigId);
            }else{
                Redis::lpush($key_0, $poolConfigId);
            }
        }
        return $res;
    }

    /**
     * 获取波波球奖池根据ID
     */
    public function getWishWheelPoolById($poolId){
        $info = DB::table($this->wPoolTable)->where('id', $poolId)->first();
        $info = self::objToArray($info);

        return $info;
    }

    /**
     * 获取波波球奖池根据奖池类型
     */
    public function getWishWheelPoolByType($status, $poolType){
        $list = DB::table($this->wPoolTable)->where('status', $status)->where('pool_type', $poolType)->get();
        $list = self::objToArray($list);

        return $list;
    }

    //获取波波球个人池根据ID
    public function getWishWheelPoolUserById($id)
    {
        $info = DB::table($this->wPoolUserTable)
            ->where('id', $id)
            ->where('is_delete', 0)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //更新波波球个人池用户记录
    public function updateWishWheelUserPoolLog($id, $propDiamondNum, $rewardDiamondNum, $drawNum)
    {
        $res = DB::table($this->wPoolUserTable)->where('id', $id)->increment('prop_diamond_num', $propDiamondNum);
        $res = DB::table($this->wPoolUserTable)->where('id', $id)->increment('reward_diamond_num', $rewardDiamondNum);
        $res = DB::table($this->wPoolUserTable)->where('id', $id)->increment('draw_num', $drawNum);

        return $res;
    }

    //更新波波球用户每日抽奖数据统计缓存
    public function updateWishWheelUserDay($userId, $propDiamondNum, $rewardDiamondNum, $drawNum)
    {
        $now = time();
        $ymd = date("Ymd", $now);
        $cacheKey = $this->userDrawNumDayKey.$ymd.':'.$userId;
        Redis::HINCRBY($cacheKey, 'prop_num', $drawNum);
        Redis::HINCRBY($cacheKey, 'prop_diamond_num', $propDiamondNum);
        Redis::HINCRBY($cacheKey, 'reward_diamond_num', $rewardDiamondNum);

        return 1;
    }

    //个人池用户自动处理移入移出
    public function handleWishWheelUserPool($userId, $poolUser)
    {
        $now = time();
        $ymd = date("Ymd", $now);
        do {
            //判断
            if(empty($poolUser)) {
                //自动移入

                //判断是否在抽取奖池
                $extractPoolUserInfo = $this->getWishWheelExtractPoolUser($userId);
                if(!empty($extractPoolUserInfo)) {
                    break;
                }

                //用户近7天转盘总累计 产出-消耗 产出/消耗
                $info = DB::table($this->wOrderTable)
                    ->where('user_id', $userId)
                    ->where('created_at', '>=', date('Y-m-d H:i:s', ($now - 2*86400)))
                    ->selectRaw('sum(prop_diamond_num) as prop_diamond_num, sum(reward_diamond_num) as reward_diamond_num')
                    ->first();
                $info = objToArray($info);
                $info['prop_diamond_num'] = empty($info['prop_diamond_num']) ? 0 : $info['prop_diamond_num'];//消耗
                $info['reward_diamond_num'] = empty($info['reward_diamond_num']) ? 0 : $info['reward_diamond_num'];//产出
                //盈亏
                $info['profit_loss'] = $info['reward_diamond_num'] - $info['prop_diamond_num'];
                //返奖率%
                $info['profit_rate'] = empty($info['prop_diamond_num']) ? 0 : round(($info['reward_diamond_num']*100)/$info['prop_diamond_num'], 2);

                //获取当前默认个人亏损池
                $config = DB::table($this->wPoolTable)->where('status', 1)->where('pool_type', 2)->where('if_default', 1)->first();
                $config = objToArray($config);
                if(!empty($config)) {
                    $in_profit_loss = empty($config['in_profit_loss']) ? 0 : $config['in_profit_loss'];//进入个人池盈亏
                    $in_profit_rate = empty($config['in_profit_rate']) ? 0 : $config['in_profit_rate'];//进入个人池返奖率%
                    $info['in_profit_loss'] = $in_profit_loss;
                    $info['in_profit_rate'] = $in_profit_rate;
                    //判断
                    if(!empty($in_profit_loss) || !empty($in_profit_rate)) {
                        $flag1 = $flag2 = 0;
                        //盈亏
                        if($in_profit_loss!=0 && $info['profit_loss']>=$in_profit_loss) {
                            $flag1 = 1;
                        }
                        //返奖率%
                        if($in_profit_rate!=0 && $info['profit_rate']>=$in_profit_rate) {
                            $flag2 = 1;
                        }

                        $flag = 0;
                        if(!empty($in_profit_loss) && !empty($in_profit_rate) && $flag1==1 && $flag2==1) {
                            $flag = 1;
                        }elseif(!empty($in_profit_loss) && empty($in_profit_rate) && $flag1==1){
                            $flag = 1;
                        }elseif(empty($in_profit_loss) && !empty($in_profit_rate) && $flag2==1){
                            $flag = 1;
                        }
                        $info['flag'] = $flag;
                        $info['flag1'] = $flag1;
                        $info['flag2'] = $flag2;

                        if($flag == 1) {
                            //移除钻石数
                            $outDiamondNum = intval($info['profit_loss']*$config['out_profit_rate']*0.01*-1);
                            $info['outDiamondNum'] = $outDiamondNum;
                            //初始化波波球个人奖池配置数据缓存指定用户
                            $poolConfigMap = $this->getWishWheelPoolConfig($config['id']);
                            if(empty($poolConfigMap)) {
                                break;
                            }
                            $poolConfigMap = array_column($poolConfigMap, 'gift_num', 'id');
                            $this->makeWishWheelSelfPoolDataByPoolIdUserId($config['id'], $userId, $poolConfigMap);
                            //新增波波球个人池用户
                            $poolUserId = $this->addWishWheelPoolUser($userId, 0, $config['id'], $outDiamondNum);
                            $info['poolUserId'] = $poolUserId;

                            break;
                        }
                    }
                }

                //获取当前默认个人盈利池
                $config = DB::table($this->wPoolTable)->where('status', 1)->where('pool_type', 3)->where('if_default', 1)->first();
                $config = objToArray($config);
                if(!empty($config)) {
                    $in_profit_loss = empty($config['in_profit_loss']) ? 0 : $config['in_profit_loss'];//进入个人池盈亏
                    $in_profit_rate = empty($config['in_profit_rate']) ? 0 : $config['in_profit_rate'];//进入个人池返奖率%
                    $info['in_profit_loss'] = $in_profit_loss;
                    $info['in_profit_rate'] = $in_profit_rate;
                    //判断
                    if(!empty($in_profit_loss) || !empty($in_profit_rate)) {
                        $flag1 = $flag2 = 0;
                        //盈亏
                        if($in_profit_loss!=0 && $info['profit_loss']<=$in_profit_loss) {
                            $flag1 = 1;
                        }
                        //返奖率%
                        if($in_profit_rate!=0 && $info['profit_rate']<=$in_profit_rate) {
                            $flag2 = 1;
                        }

                        $flag = 0;
                        if(!empty($in_profit_loss) && !empty($in_profit_rate) && $flag1==1 && $flag2==1) {
                            $flag = 1;
                        }elseif(!empty($in_profit_loss) && empty($in_profit_rate) && $flag1==1){
                            $flag = 1;
                        }elseif(empty($in_profit_loss) && !empty($in_profit_rate) && $flag2==1){
                            $flag = 1;
                        }
                        $info['flag'] = $flag;
                        $info['flag1'] = $flag1;
                        $info['flag2'] = $flag2;

                        if($flag == 1) {
                            //移除钻石数
                            $outDiamondNum = intval($info['profit_loss']*$config['out_profit_rate']*0.01*-1);
                            $info['outDiamondNum'] = $outDiamondNum;
                            //初始化波波球个人奖池配置数据缓存指定用户
                            $poolConfigMap = $this->getWishWheelPoolConfig($config['id']);
                            if(empty($poolConfigMap)) {
                                break;
                            }
                            $poolConfigMap = array_column($poolConfigMap, 'gift_num', 'id');
                            $this->makeWishWheelSelfPoolDataByPoolIdUserId($config['id'], $userId, $poolConfigMap);
                            //新增波波球个人池用户
                            $poolUserId = $this->addWishWheelPoolUser($userId, 0, $config['id'], $outDiamondNum);
                            $info['poolUserId'] = $poolUserId;

                            break;
                        }
                    }
                }

            }else{
                //自动移出
                //用户个人池记录
                $info = $this->getWishWheelPoolUserById($poolUser['id']);
                if(empty($info)) {
                    break;
                }
                //不移除
                if(empty($info['out_diamond_num'])) {
                    break;
                }
                //移除钻石数
                $out_diamond_num = empty($info['out_diamond_num']) ? 0 : $info['out_diamond_num'];
                //盈亏
                $info['profit_loss'] = $info['reward_diamond_num'] - $info['prop_diamond_num'];
                //获取奖池配置
                $config = DB::table($this->wPoolTable)->where('id', $poolUser['pool_id'])->first();
                $config = objToArray($config);

                //亏损池
                if($config['pool_type'] == 2) {
                    if($info['profit_loss'] <= $out_diamond_num) {
                        $this->wishWheelDelPoolUser($info['id'], $info['user_id'], 0);
                        $info['亏损池'] = '移除';
                    }
                    break;
                }

                //盈利池
                if($config['pool_type'] == 3) {
                    if($info['profit_loss'] >= $out_diamond_num) {
                        $this->wishWheelDelPoolUser($info['id'], $info['user_id'], 0);
                        $info['盈利池'] = '移除';
                    }
                    break;
                }
            }
        } while (false);

    }

    /**
     * 获取波波球奖池根据奖池类型
     */
    public function getWishWheelPoolByDefault($poolType){
        $info = DB::table($this->wPoolTable)->where('pool_type', $poolType)->where('if_default', 1)->first();
        $info = self::objToArray($info);

        return $info;
    }

    //新增波波球抽取奖池
    public function addWishWheelExtractPool($poolName, $poolId)
    {
        $data = [];
        $data['pool_name'] = $poolName;
        $data['pool_id'] = $poolId;
        $data['status'] = 2;

        $id = DB::table($this->wPoolExtractTable)->insertGetId($data);

        return $id;
    }

    //编辑波波球抽取奖池
    public function editWishWheelExtractPool($id, $params)
    {
        $upData = [];
        if(!empty($params['status'])) {
            $upData['status'] = $params['status'];
        }
        if(!empty($params['pool_name'])) {
            $upData['pool_name'] = $params['pool_name'];
        }

        if(empty($upData)) {
            return 0;
        }

        $res = DB::table($this->wPoolExtractTable)->where('id', $id)->update($upData);

        return $res;
    }

    /**
     * 获取波波球抽取奖池根据ID
     */
    public function getWishWheelExtractPoolById($poolId){
        $info = DB::table($this->wPoolExtractTable)->where('id', $poolId)->first();
        $info = self::objToArray($info);

        return $info;
    }

    //获取波波球抽取奖池用户
    public function getWishWheelExtractPoolUser($userId)
    {
        $info = DB::table($this->wPoolExtractUserTable)
            ->where('user_id', $userId)
            ->where('is_delete', 0)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //新增波波球抽取奖池用户
    public function addWishWheelExtractPoolUser($userId, $extractPoolId, $adminId)
    {
        $data = [];
        $data['user_id'] = $userId;
        $data['extract_pool_id'] = (int) $extractPoolId;
        $data['admin_id'] = $adminId;
        $data['add_time'] = date('Y-m-d H:i:s', time());

        $id = DB::table($this->wPoolExtractUserTable)->insertGetId($data);

        return $id;
    }

    //获取波波球抽取奖池用户根据ID
    public function getWishWheelExtractPoolUserById($id)
    {
        $info = DB::table($this->wPoolExtractUserTable)
            ->where('id', $id)
            ->where('is_delete', 0)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }

    //波波球删除抽取奖池用户
    public function wishWheelDelExtractPoolUser($id, $adminId)
    {
        $update = [];
        $update['deladmin_id'] = $adminId;
        $update['del_time'] = date('Y-m-d H:i:s', time());
        $update['is_delete'] = 1;

        $res = DB::table($this->wPoolExtractUserTable)->where('id', $id)->update($update);

        return $res;
    }

    //新增波波球抽取奖池记录
    public function addWishWheelExtractLog($data)
    {
        $id = DB::table($this->wPoolExtractLogTable)->insertGetId($data);

        return $id;
    }

    //自增波波球抽取奖池记录
    public function wishWheelExtractPoolLogIncr($id, $num)
    {
        $res = DB::table($this->wPoolExtractLogTable)->where('id', $id)->increment('true_num', $num);

        return $res;
    }

    //添加到波波球抽取奖池奖品池缓存
    public function wishWheelExtractPoolDataAdd($extractPoolId, $num)
    {
        $str = $num.'|'.microtime(true).'|'.mt_rand(1,100000);
        $cacheKey = $this->wishWheelExtractPoolDataKey.$extractPoolId;
        $res = Redis::SADD($cacheKey, $str);

        return $res;
    }

    //随机获取一个波波球抽取奖池奖品池缓存
    public function getWishWheelExtractPoolDataOne($extractPoolId)
    {
        $cacheKey = $this->wishWheelExtractPoolDataKey.$extractPoolId;
        $res = Redis::SPOP($cacheKey);
        if(!empty($res)) {
            $res = explode('|', $res);
            return empty($res[0]) ? 0 : $res[0];
        }

        return 0;
    }

    //获取波波球抽取奖池奖品池剩余数量
    public function getWishWheelExtractPoolNum($extractPoolId)
    {
        $cacheKey = $this->wishWheelExtractPoolDataKey.$extractPoolId;
        $list = Redis::SMEMBERS($cacheKey);
        if(empty($list)) {
            return [];
        }

        $res = [];
        foreach($list as $val) {
            $val = explode('|', $val);
            $giftId = $val[0];
            $res[$giftId]['gift_id'] = $giftId;
            $res[$giftId]['less_num'] = (empty($res[$giftId]['less_num']) ? 0 : $res[$giftId]['less_num']) + 1;
        }
        $res = array_values($res);

        return $res;
    }

    //获取波波球抽取奖池用户开启中的
    public function getWishWheelExtractPoolUserOpen($userId)
    {
        $info = DB::table($this->wPoolExtractUserTable.' as a')
            ->leftJoin($this->wPoolExtractTable.' as b' ,'a.extract_pool_id','=','b.id')
            ->select(['a.id','a.user_id','a.extract_pool_id','b.pool_id'])
            ->where('a.user_id', $userId)
            ->where('a.is_delete', 0)
            ->where('b.status', 1)
            ->first();
        $info = self::objToArray($info);

        return $info;
    }


}
